﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PollSystem
{
    public class PollSystem
    {
        public static List<string> GetQuestions()
        { 
            List<string> questions = new List<string>();
            PollSystemEntities entities = new PollSystemEntities();
            var allquestions = entities.Questions.ToList();
            foreach (var question in allquestions)
            {
                questions.Add(question.Question1);
            }
            return questions;
        }

        public static List<string> GetAnswers(int questionID)
        {
            List<string> answers = new List<string>();
            PollSystemEntities entities = new PollSystemEntities();
            var allAnswers = entities.Answers.Where(a => a.QuestionID == questionID);
            foreach (var answer in allAnswers)
            {
                answers.Add(answer.Answer1);
            }
            return answers;
        }

        public static Dictionary<string, int> Vote(int questionID, string answer, out string question)
        {
            Dictionary<string, int> answersCounts = new Dictionary<string, int>();
            PollSystemEntities entities = new PollSystemEntities();
            using(entities)
	        {
                question = entities.Questions.FirstOrDefault(q => q.QuestionID == questionID).Question1;

                int? votes = MakeVote(answer, entities);

                votes = GetVotes(questionID, answersCounts, entities, votes);
	        }
            return answersCounts;
        }

        private static int? GetVotes(int questionID, Dictionary<string, int> answersCounts, PollSystemEntities entities, int? votes)
        {
            var allVotes = entities.Answers.Where(a => a.QuestionID == questionID);
            foreach (var item in allVotes)
            {
                votes = item.AnswerCount;
                string currentAnswer = item.Answer1;
                int currentVotes;
                if (votes == null)
                {
                    currentVotes = 0;
                }
                else
                {
                    currentVotes = votes.Value;
                }
                answersCounts.Add(currentAnswer, currentVotes);
            }
            return votes;
        }

        private static int? MakeVote(string answer, PollSystemEntities entities)
        {
            Answer chosen = entities.Answers.FirstOrDefault(a => a.Answer1 == answer);
            int? votes = chosen.AnswerCount;
            if (votes == null)
            {
                votes = 0;
            }
            votes++;
            chosen.AnswerCount = votes;
            entities.SaveChanges();
            return votes;
        }
    }
}
